﻿using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.PB;
using Coldairarrow.Entity.Print;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using Coldairarrow.Util.ClassLibrary;
using Coldairarrow.Util.Helper;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using Quartz.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Coldairarrow.Business.PB
{
    public partial class PB_StorAreaBusiness : BaseBusiness<PB_StorArea>, IPB_StorAreaBusiness, ITransientDependency
    {
        readonly IOperator _operator;
        public PB_StorAreaBusiness(IDbAccessor db, IOperator @operator)
            : base(db)
        {
            _operator = @operator;
        }

        #region 外部接口

        // public async Task<PageResult<PB_StorArea>> GetDataListAsync(PageInput<ConditionDTO> input)
        public async Task<PageResult<PB_StorArea>> GetDataListAsync(PB_StorAreaPageInput input)
        {
            var q = GetIQueryable();
            var where = LinqHelper.True<PB_StorArea>();
            var search = input.Search;
            //q = q.Include(i => i.PB_Storage);

            //筛选
            if (!search.Keyword.IsNullOrEmpty())
            {
                where = where.And(w => w.Name.Contains(search.Keyword) || w.Code.Contains(search.Keyword)||w.StorId.Contains(search.StorageId));
            }
            if (!search.StorageId.IsNullOrEmpty())
            {
                where = where.And(p => p.StorId == search.StorageId);
            }
            if (!search.AreaType.IsNullOrEmpty())
            {
                where = where.And(p => p.Type == search.AreaType);
            }
            where = where.And(w => _operator.Property.DeptIds.Contains(w.StorId));
            return await q.Where(where).GetPageResultAsync(input);
        }

        public async Task<PB_StorArea> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        [DataAddLog(UserLogType.货区管理, "Name", "货区")]
        [DataRepeatValidate(new string[] { "StorId", "Name" }, new string[] { "仓库", "货区" }, allData: false, matchOr: false)]
        public async Task AddDataAsync(PB_StorArea data)
        {
            data.QrCode = h_StorArea + "," + data.Id + "," + data.StorId;
            await InsertAsync(data);
        }

        [DataEditLog(UserLogType.货区管理, "Name", "货区")]
        [DataRepeatValidate(new string[] { "StorId", "Name" }, new string[] { "仓库", "货区" }, allData: false, matchOr: false)]
        public async Task UpdateDataAsync(PB_StorArea data)
        {
            data.QrCode = h_StorArea + "," + data.Id + "," + data.StorId;
            await UpdateAsync(data);
        }

        [DataDeleteLog(UserLogType.货区管理, "Name", "货区")]
        public async Task DeleteDataAsync(List<string> ids)
        {

            if(await Db.GetIQueryable<PB_Rack>().AnyAsync(m=>ids.Contains(m.AreaId)))
            {
                throw new BusException("删除失败！该货区下有货架禁止删除!");
            }

            string itemid = "";
            foreach (var item in ids)
            {
                itemid += "'" + item + "',";
            }
            itemid = itemid.Substring(0, itemid.Length - 1);
            await ExecuteSqlAsync("delete  from  PB_Rack  where AreaId in (" + itemid + ")");
            await DeleteAsync(ids);
  
          
        }

        public async Task<List<PB_StorArea>> QueryStorAreaDataAsync()
        {
            var q = GetIQueryable();
            q.Where(o => _operator.Property.DeptIds.Contains(o.StorId));
            return await q.ToListAsync();
        }

        public async Task<List<PB_StorArea>> GetDataListAsync(string storId)
        {
            var q = GetIQueryable();
            q = q.Where(w => w.StorId == storId);

            return await q.ToListAsync();
        }

        public  async Task<PageResult<PB_StorAreaListDTO>> GetDataListListDtoAsync(PB_StorAreaPageInput input)
        {
            Expression<Func<PB_StorArea, Base_Department,  PB_StorAreaListDTO>> select = (a, b) => new PB_StorAreaListDTO
            {
                StorIdName = b.Name,
             
            };
            var search = input.Search;
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<Base_Department>() on a.StorId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    select @select.Invoke(a, b);
            var where = LinqHelper.True<PB_StorAreaListDTO>();
            //筛选
            if (!search.Keyword.IsNullOrEmpty())
            {
                where = where.And(w => w.Name.Contains(search.Keyword) || w.Code.Contains(search.Keyword));
            }
            if (!search.StorageId.IsNullOrEmpty())
            {
                where = where.And(p => p.StorId == search.StorageId);
            }
            if (!search.AreaType.IsNullOrEmpty())
            {
                where = where.And(p => p.Type == search.AreaType);
            }
            //where = where.And(m=>_operator.Property.DeptIds.Contains(m.StorId));
            return await q.Where(where).GetPageResultAsync(input);
        }

        /// <summary>
        /// 通过传入库区 id 打印队列
        /// </summary>
        /// <param name="id"></param>
        /// <param name="_mongodbOptions"></param>
        /// <returns></returns>
        public async Task<List<PB_StorAreaListDTO>> PrintQueue(string id, MongoDBOptions _mongodbOptions)
        {
            Expression<Func<PB_StorArea, Base_Department, PB_StorAreaListDTO>> select = (a, b) => new PB_StorAreaListDTO
            {
                StorIdName = b.Name,
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<Base_Department>() on a.StorId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    select @select.Invoke(a, b);
            string[] arr = id.Split(',');
            List<string> List = new List<string>();
            foreach (var item in arr)
            {
                List.Add(item);
            }
            string timestamp = GetTimeStamp();
            List<PrintQueue> printqueue = new List<PrintQueue>();
            q = q.Where(m => List.Contains(m.Id));
            var k = await Db.GetIQueryable<Base_Department>().Where(m => m.Id == _operator.Property.DepartmentId).FirstOrDefaultAsync();
            var res = await q.ToListAsync();
            string strguid = Guid.NewGuid().ToString("N");
            foreach (var aa in res)
            {
                PB_StorArea StorArea = new PB_StorArea();
                PrintQueue printdata = new PrintQueue();
                printdata.Id = IdHelper.GetId();
                printdata.No = aa.Code;//编号
                printdata.Name = aa.Name;
                printdata.TypeName = "";
                printdata.Date = aa.Code;//生产日期当前时间
                printdata.Dept = k.Name;//当前登录人所在组织
                printdata.QrCode = aa.QrCode;//库区id
                printdata.Type = Skill_Type.StorArea.ToString();//库区8
                printdata.Status = "0";
                printdata.Printer = _operator?.Property.Printer;
                printdata.BatchNumber = strguid;
                printdata.JobCount = res.Count;
                printqueue.Add(printdata);
            }
            MongoDBHelper mongo = new MongoDBHelper(_mongodbOptions);
            await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, printqueue);
            return res;
        }

        public async Task<AjaxResult> SelectAreaID(StorAreaPrint data, MongoDBOptions _mongodbOptions)
        {
            try
            {
                int i = 0;
                List<string> List = new List<string>();
                foreach (var item in data.StorAreaId)
                {
                 
                    List.Add(item);
                    i =List.Count;
                }

                var q = GetIQueryable();
                List<PrintQueue> printqueue = new List<PrintQueue>();
                var res = q = q.Where(m => List.Contains(m.Id));
                var k = await Db.GetIQueryable<Base_Department>().Where(m => m.Id == _operator.Property.DepartmentId).FirstOrDefaultAsync();
                string strguid = Guid.NewGuid().ToString("N");
                foreach (var item in res)
                {
                  
                    PB_StorArea storArea = new PB_StorArea();
                    PrintQueue printdata = new PrintQueue();
                    printdata.Id = IdHelper.GetId();
                    printdata.No = item.Id;//编号
                    printdata.Name = item.Name;
                    printdata.Date = DateTime.Now.ToString("yyyy-MM-dd");//生产日期当前时间
                    printdata.Dept = k.Name;//当前登录人所在组织
                    printdata.QrCode = item.QrCode;//货位编号
                    printdata.Type = Skill_Type.StorArea.ToString();//货位
                    printdata.Status = "0";
                    printdata.Printer =data.Pritntid;
                    printdata.TypeName ="库区";
                    printdata.BatchNumber = strguid;
                    printdata.Code = item.Code;
                    printdata.JobCount = i;
                    printdata.IsProduct = false;
                    printqueue.Add(printdata);
                }
                MongoDBHelper mongo = new MongoDBHelper(_mongodbOptions);
                await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, printqueue);
                AjaxResult resIn = new AjaxResult
                {
                    Success = true,
                    Msg = "打印成功"
                };
                return resIn;
            }
            catch (Exception)
            {
                AjaxResult res = new AjaxResult
                {
                    Success = false,
                    Msg = "打印失败！数据错误请检查数据"
                };
                return res;
            }
        }

        public async Task<List<PB_StorAreaListDTO>> Selectid(string id)
        {
            Expression<Func<PB_StorArea, Base_Department, PB_StorAreaListDTO>> select = (a, b) => new PB_StorAreaListDTO
            {
                StorIdName = b.Name,
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<Base_Department>() on a.StorId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    select @select.Invoke(a, b);
            string[] arr = id.Split(',');
            List<string> List = new List<string>();
            foreach (var item in arr)
            {
                List.Add(item);
            }
            q = q.Where(m => List.Contains(m.Id));
            return await q.ToListAsync();
        }

        #endregion

        #region 私有成员

        #endregion
    }
}